<template>
  <div class="login">
    <!-- 头部 -->
    <van-nav-bar title="账号登录">
      <template #left>
        <van-icon name="arrow-left"  @click="$router.back()"/>
      </template>
    </van-nav-bar>
    <!-- 表单 -->
    <van-form @submit="onSubmit">
      <van-field
        v-model="form.username"
        placeholder="请输入账号"
        :rules="[
          { required: true, message: '请填写正确的账号' },
          { pattern: /^[A-Za-z0-9]{2,6}$/, message: '请输入2-6位账号' },
        ]"
      />
      <van-field
        v-model="form.password"
        type="password"
        placeholder="请输入密码"
        :rules="[
          { required: true, message: '请填写密码' },
          { pattern: /^[A-Za-z0-9]{3,8}$/, message: '请输入3-8位密码' },
        ]"
      />
      <div style="margin: 16px">
        <van-button
          block
          type="info"
          native-type="submit"
          square
          color="#21b97a"
          >登录</van-button
        >
      </div>
    </van-form>

    <div class="zhuce">
      <a href="">还没有账号，去注册~</a>
    </div>
  </div>
</template>

<script>
import { Login } from '@/api/user.js'
import { Toast } from 'vant'
export default {
  data () {
    return {
      form: {
        username: '',
        password: ''
      }
    }
  },

  created () {},

  methods: {
    // login
    async onSubmit () {
      try {
        const res = await Login(this.form)
        console.log(res)
        if (res.data.status === 200) {
          this.$store.commit('initUser', res.data.body) // 存token
          this.$router.push('/myself')
          Toast.loading({
            message: '加载中...',
            forbidClick: true

          })
          Toast.success('登录成功')
        } else {
          Toast.fail('登录失败')
        }
      } catch (err) {
        console.dir(err)
      }
    }
  }
}
</script>

<style scoped lang="less">
/deep/.van-nav-bar {
  background-color: #21b97a;
  .van-nav-bar__title {
    color: #fff;
    font-size: 18px;
  }
  .van-icon {
    color: #fff;
  }
}
/deep/.van-form {
  .van-field__control {
    height: 60px;
    font-size: 17px;
  }
  .van-button {
    height: 50px;
    color: #fff;
    font-size: 18px;
  }
}
.zhuce {
  a {
    display: block;
    color: #666;
    font-size: 14px;
    text-align: center;
  }
}
</style>
